package com.greenantmall.activity;

import java.text.DecimalFormat;

import com.avos.avoscloud.AVUser;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.bean.Goods;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.ShareUtil;
import com.greenantmall.utils.UtilTools;
import com.greenantmall.utils.iLog;
import com.greenantmall.view.CommonDialog;
import com.greenantmall.view.PopMenu;
import com.lsarah.utils.SystemBarTintManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DetailActivity extends BaseActivity {
	public static final String TAG = "DetailActivity";
	public static final String KEY_DETAIL_OBJECTID = "KEY_DETAIL_OBJECTID";
	private ImageView iv_screenshot;
	private ImageView iv_menu;
	private ImageView iv_cart;
	private TextView iv_googds_title;
	private TextView iv_googds_desc;
	private TextView iv_googds_price;
	private TextView iv_googds_discount;
	private TextView iv_buy_count;
	private TextView iv_cart_num;
	private TextView iv_address;
	private TextView iv_buy_unit;

	// private BitmapUtils bitmapUtils;
	private Context mContext;

	private Button minus;
	private Button add;
	private Button addtocart;
	private Button iv_change_address;
	/**
	 * 每次增加减少的数量
	 */
	double step = 1;
	/**
	 * 
	 */
	private double stock = 0;
	private String goodsId;
	private Goods goods;

	private Handler mHandler = new Handler();

	private RelativeLayout nodataView;
	private RelativeLayout nodataResultView;
	private RelativeLayout app_detail_bottom_bar_rl;
	private LinearLayout dataView;
	private LinearLayout makeCallView;

	// 电话号码
	private String teleP = "";

	DecimalFormat df = new DecimalFormat("#########.##");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;

		SystemBarTintManager.setContentView(this, R.layout.detail, getResources().getColor(R.color.green));
		initViews();

		processBundle();
		registerPrivateReceiver();

	}

	private void registerPrivateReceiver() {
		IntentFilter downloadManagerFilter = new IntentFilter();
		downloadManagerFilter.addAction(Const.SHOPPING_CART_CHANGED);
		this.registerReceiver(downloadManagerReceiver, downloadManagerFilter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterPrivateReceiver();
	}

	private void unregisterPrivateReceiver()

	{
		this.unregisterReceiver(downloadManagerReceiver);
	}

	private BroadcastReceiver downloadManagerReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (Const.SHOPPING_CART_CHANGED.equals(intent.getAction())) {
				processCartNums();
			}
		}
	};

	private void processCartNums() {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				/**
				 * 已经添加到购物车
				 */
				if (AntHomeApplication.shoppingMap.containsKey(goodsId)) {
					ShoppingCart shoppingCart = AntHomeApplication.shoppingMap.get(goodsId);
					iv_buy_count.setText(String.valueOf(shoppingCart.getQuantity()));
					addtocart.setText(mContext.getString(R.string.goods_detail_addcart_already));
					processButtonIsClickAble();
				} else {
					iv_buy_count.setText("0");
					addtocart.setText(mContext.getString(R.string.goods_detail_addcart));
					processButtonIsClickAble();
				}
				int size = UtilTools.getShoppingCartDatas().size();
				iv_cart.setBackgroundResource(R.drawable.bt_cart);
				if (size > 0) {
					iv_cart_num.setText(String.valueOf(size));
					iv_cart_num.setVisibility(View.VISIBLE);
				} else {
					iv_cart_num.setVisibility(View.GONE);
				}
			}
		});
	}

	/**
	 * 初始化界面设置
	 * 
	 * @since 3.8
	 */
	private void initViews() {
		// 截图设置为正方形
		iv_screenshot = (ImageView) this.findViewById(R.id.iv_screenshot);
		LayoutParams params = iv_screenshot.getLayoutParams();
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		params.height = width;
		iv_screenshot.setLayoutParams(params);

		iv_menu = (ImageView) this.findViewById(R.id.iv_menu);
		iv_cart = (ImageView) this.findViewById(R.id.iv_cart);
		iv_googds_title = (TextView) this.findViewById(R.id.iv_googds_title);
		iv_googds_desc = (TextView) this.findViewById(R.id.iv_googds_desc);

		iv_googds_price = (TextView) this.findViewById(R.id.iv_googds_price);
		iv_googds_discount = (TextView) this.findViewById(R.id.iv_googds_discount);
		iv_buy_count = (TextView) this.findViewById(R.id.iv_buy_count);
		iv_cart_num = (TextView) this.findViewById(R.id.iv_cart_num);
		iv_address = (TextView) this.findViewById(R.id.iv_address);
		iv_buy_unit = (TextView) this.findViewById(R.id.iv_buy_unit);
		nodataView = (RelativeLayout) this.findViewById(R.id.nodataView);
		nodataResultView = (RelativeLayout) this.findViewById(R.id.nodataResultView);
		app_detail_bottom_bar_rl = (RelativeLayout) this.findViewById(R.id.app_detail_bottom_bar_rl);
		dataView = (LinearLayout) this.findViewById(R.id.dataView);
		makeCallView = (LinearLayout) this.findViewById(R.id.makeCallView);

		iv_address.setText(UtilTools.getServerSection(getApplication()).getAddress());

		iv_buy_count.setText("0");

		minus = (Button) this.findViewById(R.id.minus);
		minus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (UtilTools.isUserLogined(mContext)) {

				} else {
					finish();
					return;
				}

				minus.setEnabled(false);
				minus.setClickable(false);

				String text = addtocart.getText().toString();
				double quantity = Double.parseDouble(iv_buy_count.getText().toString());
				if (mContext.getString(R.string.goods_detail_addcart_already).equals(text)
						|| mContext.getString(R.string.goods_detail_addcart_modify).equals(text)) {

					if (quantity - step < step) {
						if (AntHomeApplication.shoppingMap.containsKey(goodsId)) {
							ShoppingCart shoppingCart = AntHomeApplication.shoppingMap.get(goodsId);
							RetrieveDataAsyn.getInstance().removeShoppingCart(shoppingCart, 0,
									new RetrieveDataListener() {

								@Override
								public void dataRetrieved(int requestId, Object data) {
									if (data != null) {
										iv_buy_count.setText("0");
									}
									minus.setEnabled(true);
									minus.setClickable(true);
								}
							});
						}

					} else {

						double temp = quantity - step;
						modifyGoodsQuantity(temp);

					}

				} else {
					
//					if (quantity - step < step) {
//						iv_buy_count.setText("0");
//					} else {
//						iv_buy_count.setText(String.valueOf(quantity - step));
//					}
//
//					modifyGoodsQuantity();

				}

//				processShoppingCart(Double.parseDouble(iv_buy_count.getText().toString()));
			}
		});
		add = (Button) this.findViewById(R.id.add);
		add.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (UtilTools.isUserLogined(mContext)) {

				} else {
					finish();
					return;
				}
				add.setEnabled(false);
				add.setClickable(false);
				// addtocart
				String text = addtocart.getText().toString();

				final double quantity = Double.parseDouble(iv_buy_count.getText().toString());

				iLog.d(TAG, "addtocart:" + text + " " + Double.parseDouble(iv_buy_count.getText().toString()));
				if (mContext.getString(R.string.goods_detail_addcart).equals(text)) {

					RetrieveDataAsyn.getInstance().addToShoppingCart(getUserId(), AntHomeApplication.sectionNum, goods,
							step, 0, new RetrieveDataListener() {

						@Override
						public void dataRetrieved(int requestId, Object data) {
							ShoppingCart shoppingCart = (ShoppingCart) data;

							if (shoppingCart != null) {
								iv_buy_count.setText(String.valueOf(shoppingCart.getQuantity()));
								Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
								sendBroadcast(intent);
							}
							add.setEnabled(true);
							add.setClickable(true);
						}
					});

				} else {

					 double tempquantity=0;
					if (quantity + step >= stock) {
						tempquantity=stock;
//						iv_buy_count.setText(String.valueOf(stock));
					} else {
						tempquantity=quantity + step;
//						iv_buy_count.setText(String.valueOf(quantity + step));
					}

					modifyGoodsQuantity(tempquantity);

				}


//				processShoppingCart(Double.parseDouble(iv_buy_count.getText().toString()));
			}
		});
		addtocart = (Button) this.findViewById(R.id.addtocart);
		addtocart.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (UtilTools.isUserLogined(mContext)) {

				} else {
					finish();
					return;
				}
				// addtocart
				String text = addtocart.getText().toString();
				iLog.d(TAG, "addtocart:" + text + " " + Double.parseDouble(iv_buy_count.getText().toString()));
				if (mContext.getString(R.string.goods_detail_addcart_already).equals(text)) {

					return;
				} else if (mContext.getString(R.string.goods_detail_addcart_modify).equals(text)) {
					ShoppingCart shoppingCart = AntHomeApplication.shoppingMap.get(goodsId);
					shoppingCart.setQuantity(Double.parseDouble(iv_buy_count.getText().toString()));

					RetrieveDataAsyn.getInstance().updateShoppingCart(shoppingCart, getUserId(), 0,
							new RetrieveDataListener() {

						@Override
						public void dataRetrieved(int requestId, Object data) {
							if (data != null) {
								AntHomeApplication.shoppingMap.put(goodsId, (ShoppingCart) data);
								addtocart.setText(mContext.getString(R.string.goods_detail_addcart_already));
								processButtonIsClickAble();
							} else {
								UtilTools.showMyToast(mContext, mContext.getString(R.string.failed));
							}
						}
					});

				} else if (mContext.getString(R.string.goods_detail_addcart).equals(text)) {

					RetrieveDataAsyn.getInstance().addToShoppingCart(getUserId(), AntHomeApplication.sectionNum, goods,
							Double.parseDouble(iv_buy_count.getText().toString()), 0, new RetrieveDataListener() {

						@Override
						public void dataRetrieved(int requestId, Object data) {
							ShoppingCart shoppingCart = (ShoppingCart) data;
							if (shoppingCart != null) {
								AntHomeApplication.shoppingMap.put(goodsId, shoppingCart);
								Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
								sendBroadcast(intent);
							}

						}
					});

				}

				processCartNums();
			}
		});

		final PopMenu popMenu = new PopMenu(this);
		String[] detailmenus = this.getResources().getStringArray(R.array.detail_menus);
		int[] drawables = { R.drawable.detail_favorite, R.drawable.detail_share, R.drawable.detail_main };
		popMenu.addItems(detailmenus, drawables);
		popMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				popMenu.dismiss();
				iLog.d(TAG, "popMenu dismiss" + arg2);
				if (arg2 == 0) {
					if (UtilTools.isUserLogined(mContext)) {
						// 收藏
						RetrieveDataAsyn.getInstance().addToFav(goodsId, AVUser.getCurrentUser().getObjectId(), 0,
								new RetrieveDataListener() {

							@Override
							public void dataRetrieved(int requestId, Object data) {
								if (data == null) {
									// 收藏失败
									UtilTools.showMyToast(mContext,
											mContext.getString(R.string.goods_detail_fav_failed));
								} else {
									// 收藏成功
									UtilTools.showMyToast(mContext,
											mContext.getString(R.string.goods_detail_fav_success));
								}
							}
						});
					}

				} else if (arg2 == 1) {
					// 分享
					ShareUtil.getInstance(mContext).share();

				} else if (arg2 == 2) {
					// 跳转首页
					Intent intent = new Intent(mContext, PortalActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
					mContext.startActivity(intent);
					finish();
				}

			}
		});
		iv_menu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				popMenu.showAsDropDown(iv_menu);
			}
		});

		iv_change_address = (Button) this.findViewById(R.id.iv_change_address);
		iv_change_address.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, SelectAreaActivity.class);
				mContext.startActivity(intent);
				finish();
			}
		});
	}

	private void processShoppingCart(double quantity) {

		if (AntHomeApplication.shoppingMap.containsKey(goodsId)) {
			ShoppingCart shoppingCart = AntHomeApplication.shoppingMap.get(goodsId);
			Log.d(TAG, "getQuantity:" + quantity + " quantity:" + shoppingCart.getQuantity());
			if (Math.abs(shoppingCart.getQuantity() - quantity) <= 0.00001) {
				addtocart.setText(mContext.getString(R.string.goods_detail_addcart_already));
				processButtonIsClickAble();
			} else {
				// 修改购买数量
				addtocart.setText(mContext.getString(R.string.goods_detail_addcart_modify));
				processButtonIsClickAble();
			}

		}
	}

	private void modifyGoodsQuantity(double quantity) {

		ShoppingCart shoppingCart = AntHomeApplication.shoppingMap.get(goodsId);
		if (shoppingCart != null) {
			shoppingCart.setQuantity(quantity);

			RetrieveDataAsyn.getInstance().updateShoppingCart(shoppingCart, getUserId(), 0, new RetrieveDataListener() {

				@Override
				public void dataRetrieved(int requestId, Object data) {
					if (data != null) {
						ShoppingCart tempShoppingCart=(ShoppingCart)data;
						iv_buy_count.setText(String.valueOf(tempShoppingCart.getQuantity()));
						addtocart.setText(mContext.getString(R.string.goods_detail_addcart_already));
					} else {
						UtilTools.showMyToast(mContext, mContext.getString(R.string.failed));
					}
					processButtonIsClickAble();
				}
			});
		}

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		processBundle();
	}

	private void processBundle() {
		String objectId = null;
		Intent intent = getIntent();
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				objectId = bundle.getString(KEY_DETAIL_OBJECTID);

			}
		}
iLog.d("processBundle getGoodsDetail detail:"+objectId);
		RetrieveDataAsyn.getInstance().getGoodsDetail(objectId, 0, new RetrieveDataListener() {

			@Override
			public void dataRetrieved(int requestId, Object data) {
				goods = (Goods) data;
				if (goods != null) {
					Log.d(TAG, "goods.getImageUrl():" + goods.getImageUrl());
					ImageLoader.getInstance().displayImage(goods.getImageUrl(), iv_screenshot,
							AntHomeApplication.imageDisplayOptions);
					iv_googds_title.setText(goods.getDescriptionAndSpecs());
					// 实际的购买单位
					iv_buy_unit.setText(goods.getWeighUnit());

					stock = goods.getStock();// 总量
					goodsId = goods.getObjectId();
					String unit = goods.getUnit();
					;
					step = goods.getWeighStep();
					// 商品为可称重的
					if (goods.isWeighAble()) {
						iv_googds_desc.setVisibility(View.VISIBLE);
					} else {
						iv_googds_desc.setVisibility(View.GONE);
					}
					iv_buy_count.setText("0");
					iv_googds_discount.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 中划线

					String price = "￥" + df.format(goods.getPrice());

					double discount = goods.getDiscount();
					if (discount <= 0) {
						String strs = price + "/ " + unit;
						SpannableStringBuilder style = new SpannableStringBuilder(strs);
						style.setSpan(new ForegroundColorSpan(Color.RED), 0, price.length(),
								Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
						iv_googds_price.setText(style);
					} else {
						price = "￥" + (df.format(goods.getPrice() * goods.getDiscount() / 10));
						String strs = price + "/ " + unit;
						SpannableStringBuilder style = new SpannableStringBuilder(strs);
						style.setSpan(new ForegroundColorSpan(Color.RED), 0, price.length(),
								Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
						iv_googds_price.setText(style);

						iv_googds_discount.setText("￥" + goods.getPrice() + "/ " + unit);
					}

					processCartNums();

					try {
						teleP = String.valueOf(AntHomeApplication.serviePhone.getPhone());
					} catch (Exception e) {
						e.printStackTrace();
					}

					try {
						String sPhone = AntHomeApplication.storeInfos.get(goods.getStoreId()).getPhone();
						if (!TextUtils.isEmpty(sPhone)) {
							teleP = sPhone;
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

					if (TextUtils.isEmpty(teleP)) {
						makeCallView.setVisibility(View.GONE);
					}
					dataView.setVisibility(View.VISIBLE);
				} else {
					Log.d(TAG, "goods.getImageUrl() is null:");
					nodataResultView.setVisibility(View.VISIBLE);
					app_detail_bottom_bar_rl.setVisibility(View.GONE);
				}

				nodataView.setVisibility(View.INVISIBLE);
				// 售罄，无存货，售罄
				processButtonIsClickAble();

			}
		});
	}

	private void processButtonIsClickAble() {
		// 售罄，无存货，售罄
		if (goods != null && !goods.getIsOnShelf() ||goods != null && goods.getStock() <= 0.00001 || goods != null &&goods.getShowTag() == 3) {
			minus.setEnabled(false);
			minus.setClickable(false);
			add.setEnabled(false);
			add.setClickable(false);
			addtocart.setEnabled(false);
		} else {
			minus.setEnabled(true);
			minus.setClickable(true);
			add.setEnabled(true);
			add.setClickable(true);

			double quantity = 0;
			try {
				quantity = Double.parseDouble(iv_buy_count.getText().toString());
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			if (AntHomeApplication.shoppingMap.containsKey(goodsId)) {
				ShoppingCart shoppingCart = AntHomeApplication.shoppingMap.get(goodsId);
				if (Math.abs(shoppingCart.getQuantity() - quantity) <= 0.00001) {
					addtocart.setText(mContext.getString(R.string.goods_detail_addcart_already));
					addtocart.setEnabled(false);
				} else {
					// 修改购买数量
					addtocart.setText(mContext.getString(R.string.goods_detail_addcart_modify));
					addtocart.setEnabled(true);
				}

			}else{
				addtocart.setEnabled(true);
			}
		}
	}

	public void goBack(View view) {
		finish();
	}

	public void goToCart(View view) {
		if (UtilTools.isUserLogined(this)) {
			Intent intent = new Intent(this, ShoppingCartActivity.class);
			if (UtilTools.isSPStore(goods, null)) {
				intent.putExtra(ShoppingCartActivity.KEY_SP_SHOPPING_CART, true);
			} else {
				intent.putExtra(ShoppingCartActivity.KEY_SP_SHOPPING_CART, false);
			}
			intent.putExtra(ShoppingCartActivity.KEY_STORE_ID, goods.getStoreId());
			startActivity(intent);
		} else {
			finish();
		}

	}

	public void makeaCall(View view) {

		if (!TextUtils.isEmpty(teleP)) {
			CommonDialog errDialog = new CommonDialog(mContext, R.style.ExitDialogStyle,
					mContext.getString(R.string.common_title), mContext.getString(R.string.orderdetail_call));
			errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

				@Override
				public void sureClicked() {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + teleP));
					startActivity(intent);
				}
			});
			errDialog.show();

		}

	}
}
